package com.hdoit.apollo.web.cargo.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.cargo.model.Collocation;
import com.hdoit.apollo.logical.cargo.model.Standard;
import com.hdoit.apollo.logical.cargo.model.StandardProperty;
import com.hdoit.apollo.logical.cargo.model.StandardPropertyUser;
import com.hdoit.apollo.logical.cargo.model.StandardUser;
import com.hdoit.apollo.logical.cargo.service.ICargoService;
import com.hdoit.apollo.logical.cargo.service.ICollocationService;
import com.hdoit.apollo.logical.cargo.service.IStandardPropertyService;
import com.hdoit.apollo.logical.cargo.service.IStandardPropertyUserService;
import com.hdoit.apollo.logical.cargo.service.IStandardService;
import com.hdoit.apollo.logical.cargo.service.IStandardUserService;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.stock.model.Stock;
import com.hdoit.apollo.logical.stock.model.StockCollocation;
import com.hdoit.apollo.logical.stock.service.IStockCollocationService;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.hdoit.apollo.logical.viewmodel.cargo.StandardPropertySearch;
import com.hdoit.apollo.logical.viewmodel.cargo.StandardUserSearch;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;

/**
 * @author      humaoshu
 * @email       
 * @createtime  2018年05月04日 08:40:46
 * @comment
 */
@Controller
@RequestMapping(value = "/cargo/standardUser/")
public class StandardUserController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/cargo/standardUser/";
    }

    @Autowired
    private IStandardPropertyUserService standardPropertyUserService;
    
    @Autowired
    private IStandardUserService standardUserService;
    
    @Autowired
    private IStandardService standardService;
    
    @Autowired
    private IStandardPropertyService standardPropertyService;
    
    @Autowired
    private IStockService stockService;
    
    @Autowired
	private IStockCollocationService stockCollocationService;
    
	@Autowired
	private ICollocationService collocationService;
	
	@Autowired
	private ICargoService cargoService;

    private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="detailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,StandardUserSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(standardPropertyUserService.queryCountMP(search));
        //List<StandardUser> standardUsers= standardUserService.queryListMP(search,pagerModel);
        
        List<StandardPropertyUser> standardPropertyUsers=standardPropertyUserService.queryListMP(search,pagerModel); 
        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        //model.addAttribute("standardUsers", standardUsers);
        model.addAttribute("standardPropertyUsers", standardPropertyUsers);
        model.addAttribute("standardUserSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String standardUserDetailed(Model model,String key,String cargoId){
        StandardUser standardUser=new StandardUser();
        
        List<StandardUser> standardUsers=new ArrayList<StandardUser>();
        
        System.err.println(cargoId+"胡茂树");
        
        List<Standard> standards=new ArrayList<Standard>();
        List<StandardProperty> standardProperties=new ArrayList<StandardProperty>();
        //SearchModel search=new SearchModel();
        StandardPropertySearch search=new StandardPropertySearch();
        standards=standardService.queryListMP(search,null);
        standardProperties=standardPropertyService.queryListMP(search,null);
        
       
        if(!StringUtils.isEmpty(key)){
            standardUser=standardUserService.queryModel(key);
            
            System.err.println(standardUser);
        }
        
        if(!StringUtils.isEmpty(cargoId)){
        	standardUsers=standardUserService.queryListByCargoId(cargoId);
        }
        model.addAttribute("standardUser", standardUser);
        model.addAttribute("standardUsers", standardUsers);
        model.addAttribute("standardsJson", JsonUtils.writeValueAsString(standards));
        model.addAttribute("standardPropertiesJson", JsonUtils.writeValueAsString(standardProperties));
        return view(detailedViewName);
    }
    
   

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,StandardUser standardUser){
    	
    	List<StandardPropertyUser> standardPropertyUsers=new ArrayList<StandardPropertyUser>();
    	List<StandardUser> standardUsers=new ArrayList<StandardUser>();
    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    	Collocation collocation=new Collocation();
    	StockCollocation stockCollocation=new StockCollocation();
    	
    	if (!StringUtils.isEmpty(standardUser.getOtherPropertyNames())&&!StringUtils.isEmpty(standardUser.getStandardUserIds())) {
			String[] otherNames=standardUser.getOtherPropertyNames().split(",");
			String[] standardUserIds=standardUser.getStandardUserIds().split(",");
			
			for (int i = 0; i < otherNames.length; i++) {
				
				StandardPropertyUser standardPropertyUser=new StandardPropertyUser(); 
				
				standardPropertyUser.setStandardPropertyUserId(CommonUtils.getKeyId());
				standardPropertyUser.setStandardUserId(standardUserIds[i]);
				standardPropertyUser.setOtherPropertyName(otherNames[i]);
				standardPropertyUser.setShopId(shop.getShopId());
				standardPropertyUser.setDeleteMark(YesOrNoInteger.no);
				standardPropertyUser.setCreateUserId(getLoginModel().getLoginId());
				standardPropertyUser.setCreateUserName(getLoginModel().getLoginName());
				standardPropertyUser.setCreateDate(DateUtils.getCurrent());
				standardPropertyUser.setModelStatus(ModelStatus.add);
				
				standardPropertyUsers.add(standardPropertyUser);
			}
			
			if (otherNames.length==1) {
				collocation.setCollocationId(CommonUtils.getKeyId());
				collocation.setCargoId(standardUser.getCargoId());
				collocation.setPropertyNameOne(otherNames[0]);
				collocation.setCostPrice(Double.parseDouble(standardUser.getSalePrice()));
				collocation.setSalePrice(Double.parseDouble(standardUser.getCostPrice()));
				collocation.setCollocationNo(standardUser.getCollocationNo());
				collocation.setShopId(shop.getShopId());
				collocation.setDeleteMark(YesOrNoInteger.no);
				collocation.setCreateUserId(getLoginModel().getLoginId());
				collocation.setCreateUserName(getLoginModel().getLoginName());
				collocation.setCreateDate(DateUtils.getCurrent());
				collocation.setModelStatus(ModelStatus.add);
			}
			
			if (otherNames.length==2) {
				collocation.setCollocationId(CommonUtils.getKeyId());
				collocation.setCargoId(standardUser.getCargoId());
				collocation.setPropertyNameOne(otherNames[1]);
				collocation.setPropertyNameTwo(otherNames[0]);
				collocation.setCostPrice(Double.parseDouble(standardUser.getSalePrice()));
				collocation.setSalePrice(Double.parseDouble(standardUser.getCostPrice()));
				collocation.setCollocationNo(standardUser.getCollocationNo());
				collocation.setShopId(shop.getShopId());
				collocation.setDeleteMark(YesOrNoInteger.no);
				collocation.setCreateUserId(getLoginModel().getLoginId());
				collocation.setCreateUserName(getLoginModel().getLoginName());
				collocation.setCreateDate(DateUtils.getCurrent());
				collocation.setModelStatus(ModelStatus.add);
			}
			
			Stock stock=stockService.queryModelByCargoId(standardUser.getCargoId());
			
			
			Double collocationDebt=0.0;	
			
			stockCollocation.setStockCollocationId(CommonUtils.getKeyId());
			stockCollocation.setStockId(stock.getStockId());
			stockCollocation.setCollocationId(collocation.getCollocationId());
			stockCollocation.setCollocationDebt(collocationDebt);
			stockCollocation.setCollocationNum(collocationDebt);
			stockCollocation.setCreateDate(DateUtils.getCurrent());
			stockCollocation.setDeleteMark(YesOrNoInteger.no);
			stockCollocation.setModelStatus(ModelStatus.add);
			stockCollocation.setShopId(shop.getShopId());
	
			
		}
    

        ActionResult actionResult;
        
        if(stockCollocationService.applyChange(stockCollocation)&&standardPropertyUserService.applyChanges(standardPropertyUsers)&&collocationService.applyChange(collocation)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("standardUsers", standardUsers);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(standardUserService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
}